<template>
  <div class="dashboard-editor-container">
    <div>
      <el-card>
        <el-form :model="ruleForm" style="margin-top:10px;" size="mini" label-position="top" ref="ruleForm">
          <el-row :gutter="10">
            <el-col :lg="4" :md="6">
              <el-form-item label="渠道" prop='CHANNELTYPE'>
                <el-select v-model="ruleForm.CHANNELTYPE" filterable @change="changeChannel" clearable
                  placeholder="请选择业务渠道">
                  <el-option v-for="item in channelOption" :key="item.FIELDKEY" :label="item.FIELDVALUE"
                    :value="item.FIELDKEY"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item label="业务类型" prop='BUSINESSTYPE'>
                <el-select v-model="ruleForm.BUSINESSTYPE" filterable clearable placeholder="请选择业务类型" @change="changeType">
                  <el-option v-for="item in typeOption" :key="item.BUSINESSTYPE" :label="item.BUSINESSNAME"
                    :value="item.BUSINESSTYPE"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item label="交易码" prop='TRANSCODE'>
                <el-select v-model="ruleForm.TRANSCODE" filterable clearable placeholder="请输入交易码">
                  <el-option v-for="item in relationOption" :key="item.TRANSCODE"
                    :label="item.TRANSCODE+'—'+item.TRANSNAME" :value="item.TRANSCODE"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item label="ID" prop='ID'>
                <el-input size="mini" placeholder="请输入ID" v-model="ruleForm.ID"></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12" class="searchBtnMarginTop" >
              <el-button type="primary" icon="el-icon-search" :loading="loading" size="mini" @click="queryImportData">查询
              </el-button>
              <el-button type='warning' size='mini' icon='el-icon-refresh' @click="clearForm('ruleForm')">重置</el-button>
              <el-button type="success" size="mini" icon="el-icon-plus" @click="openEditDialog('','add')">新增
              </el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="tableData" border highlight-current-row class="tableMarginTop">
          <el-table-column prop="ID" align="center" label="ID"></el-table-column>
          <el-table-column prop="CHANNELTYPE" align="center" label="渠道类型" :formatter="dataFormat"></el-table-column>
          <el-table-column prop="BUSINESSTYPE" align="center" label="业务类型" :formatter="dataFormat"></el-table-column>
          <el-table-column prop="TRANSCODE" align="center" label="交易码" :formatter="dataFormat"></el-table-column>
          <el-table-column prop="SCORETEMPLATEID" align="center" label="模板编号"></el-table-column>
          <el-table-column prop="SCORETEMPLATEID" align="center" label="模板名称" :formatter="dataFormat"></el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <div>
                <el-button type="warning" size="mini" icon="el-icon-edit" @click="openEditDialog(scope.row,'update')">
                  修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="delImportData(scope.row)">删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-row>
          <el-col>
            <el-pagination style="text-align: right; margin-top:20px;" :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize" @size-change="handleInSizeChange" @current-change="handleInCurrentChange"
              :current-page="currpage" background layout="total,sizes, prev, pager, next, jumper" :total="tableTotal">
            </el-pagination>
          </el-col>
        </el-row> -->
      </el-card>
    </div>
    <component :is="dialogList.editDialog" :option="editOptions" @refreshTable="queryImportData"></component>
  </div>
</template>

<script>
  // 发送接口
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import request from "@/common/utils/requestQC";
  import queyData from "@/message/QCManage/scoreTemplate/templateChannelManage/templateChannelManageQuery";
  import delData from "@/message/QCManage/scoreTemplate/templateChannelManage/templateChannelManageDel";
  import toolBox from "@/common/utils/toolBox";
  import editDialog from "./dialog/editDialog";
  import dictionary from '@/message/wfm/baseData/dictionaryManage/dictionaryQuery'
  import requestWFM from "@/common/utils/requestWFM";
  import queyTemp from "@/message/QCManage/scoreTemplate/scoreTemplate/scoreTemplateQuery";
  import relation from "@/message/QCManage/scoreTemplate/templateChannelManage/templateRelation";
  import type from "@/message/QCManage/scoreTemplate/templateChannelManage/channelType";

  export default {
    name: '',
    data() {
      return {
        relationOption: [],
        typeOption: [],
        ID: '',
        TRANSCODE: '',
        channelOption: [], //渠道类型
        dialogList: {
          editDialog
        },
        editOptions: {
          isShow: false,
          title: '',
          row: {},
          flag: ''
        },
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        tableData: [],
        ruleForm: {
          CHANNELTYPE: '', //渠道
          BUSINESSTYPE: '', //业务类型
          TRANSCODE: '',
          ID: ''
        },
        loading: false,
        SCORETEMPLATENAME: "",
        BUSINESSTYPE: "",
        CHANNELTYPE: "",
        CREATIVEPERSON: "",
        SCOREMAJORITEMNAME: "",
        SCOREMINORTERMNAME: "",
        SCORETEMPLATEIDOption: []
      }
    },
    computed: {},
    created() {

    },
    mounted() {
      this.queryImportData();
      this.dictionaryQuery('CHANNELTYPE').then(value => this.channelOption = value);
      this.typeQuery()
      this.queryTemplate();
    },
    watch: {},
    methods: {
      changeType(){
        this.channelTypeQuery()
      },
      changeChannel() {
        this.typeQuery()
      },
      unqiueArr(arr) {
        let obj={}
        arr = arr.reduce( (a, b) => {
          obj[b.BUSINESSTYPE] ? '' : obj[b.BUSINESSTYPE] = true && a.push(b);
          return a;
        }, [])
        return arr;
      },
      //查询业务类型
      async typeQuery() {
        this.typeOption = []
        let resBody = new type();
        resBody.data.CHANNELTYPE = this.ruleForm.CHANNELTYPE
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          let arr  = response.BODY.RSPSTRUCT;
          console.log(arr)
          if (this.ruleForm.CHANNELTYPE == '') {
            this.typeOption = this.unqiueArr(arr)
          }else{
            this.typeOption = arr
          }
          this.channelTypeQuery()
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      //查询渠道业务关系
      async channelTypeQuery() {
        this.relationOption = []
        let resBody = new relation();
        resBody.data.CHANNELTYPE = this.ruleForm.CHANNELTYPE
        resBody.data.BUSINESSTYPE = this.ruleForm.BUSINESSTYPE
        resBody.data.TRANSCODE = this.ruleForm.TRANSCODE
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.relationOption = response.BODY.RSPSTRUCT;
          this.relationOption.forEach(item => {
            this.typeOption.forEach(ele => {
              if (item.BUSINESSTYPE == ele.FIELDKEY) {
                item.BUSINESSNAME = ele.FIELDVALUE
              }
            })
          })
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      async dictionaryQuery(type) {
        let resBody = new dictionary();
        resBody.data.FIELDCODE = type
        resBody.data.CurrPage = 1
        resBody.data.PageRowNum = 400
        let response = await requestWFM(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          return response.BODY.FIEDATA;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },

      // 查询评分模板
      async queryTemplate() {
        let resBody = new queyTemp()
        resBody.data.PageFlag = 4;
        resBody.data.CurrPage = 1;
        resBody.data.PageRowNum = 100 + '';
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.SCORETEMPLATEIDOption = response.BODY.REQBODY
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },

      dataFormat(row, column) {
        //枚举设备形式
        if (column.property == "CHANNELTYPE")
          return this.findName(this.channelOption, row[column.property]);
        if (column.property == "BUSINESSTYPE")
          return this.findType(this.typeOption, row[column.property]);
        if (column.property == "TRANSCODE")
          return this.findCode(this.relationOption, row[column.property]);
        if (column.property == "SCORETEMPLATEID")
          return this.findTemplate(this.SCORETEMPLATEIDOption, row[column.property]);
      },
      findCode(arr, val) {
        let data = arr.filter(item => {
          return item.TRANSCODE == val
        })
        if (data.length)
          return data[0].TRANSCODE + ' - ' + data[0].TRANSNAME
      },
      findType(arr,val){
        let data = arr.filter(item => {
          return item.BUSINESSTYPE == val
        })
        if (data.length)
          return data[0].BUSINESSTYPE+ '-'+data[0].BUSINESSNAME
      },
      findName(arr, val) {
        let data = arr.filter(item => {
          return item.FIELDKEY == val
        })
        if (data.length)
          return data[0].FIELDKEY + ' - ' + data[0].FIELDVALUE
      },
      findTemplate(arr, val) {
        let data = arr.filter(item => {
          return item.SCORETEMPLATEID == val
        })
        if (data.length)
          return data[0].SCORETEMPLATENAME
      },
      //打开修改新增Dialog
      async openEditDialog(row, flag) {
        this.editOptions.flag = flag
        this.editOptions.channelOption = this.channelOption
        this.editOptions.typeOption = this.typeOption
        this.editOptions.SCORETEMPLATEIDOption = this.SCORETEMPLATEIDOption
        let resBody = new relation()
        resBody.data.CHANNELTYPE = row.CHANNELTYPE;
        resBody.data.BUSINESSTYPE = row.BUSINESSTYPE;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.editOptions.relationOption = response.BODY.RSPSTRUCT;
          if (flag == 'add') {
            this.editOptions.isShow = true
            this.editOptions.title = '新增评分模板数据'
          } else {
            this.editOptions.isShow = true
            this.editOptions.title = '修改评分模板数据'
            this.editOptions.row = row
          }
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }

      },
      //前端分页
      handleInCurrentChange(val) {
        this.currpage = val;
        // console.log(`当前页: ${val}`);
        this.queryImportData()
      },
      handleInSizeChange(val) {
        this.pageSize = val;
        this.queryImportData()
      },
      //删除导入字段
      delImportData(row) {
        this.$confirm('此操作将删除该字段, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let resBody = new delData()
          resBody.data.ID = row.ID;
          let response = await request(resBody);
          if (response.SYS_HEAD.ReturnCode == "000000") {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.queryImportData()
          } else {
            this.$message({
              type: "error",
              message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      async queryImportData() {
        let resBody = new queyData()
        resBody.data.CHANNELTYPE = this.ruleForm.CHANNELTYPE;
        resBody.data.BUSINESSTYPE = this.ruleForm.BUSINESSTYPE;
        resBody.data.ID = this.ruleForm.ID;
        resBody.data.TRANSCODE = this.ruleForm.TRANSCODE;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.tableData = response.BODY.RSPSTRUCT.length==undefined?[]:response.BODY.RSPSTRUCT;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 重置查询条件
      clearForm(item) {
        // 重置表格
        this.$refs["" + item].resetFields();
      },
    }
  }

</script>

<style rel="stylesheet/scss" lang="scss" scoped>


</style>
